package com.ptt.sqm.activity;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;

import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BlurMaskFilter;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.EmbossMaskFilter;
import android.graphics.MaskFilter;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.GoogleMap.OnMyLocationChangeListener;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.ptt.sqm.model.AssessItem;
import com.ptt.sqm.model.AssessItemChoice5018;
import com.ptt.sqm.model.AssessItemList;
import com.ptt.sqm.model.AssessSubject5019;
import com.ptt.sqm.model.AssessSuggestion5034;
import com.ptt.sqm.model.AssessTran;
import com.ptt.sqm.model.AssessTranList;
import com.ptt.sqm.model.CustomerInfo;
import com.ptt.sqm.model.InsertAssessTranResult;
import com.ptt.sqm.model.Login;
import com.ptt.sqm.model.SaveDraftAssessTranResult;
import com.ptt.sqm.model.SubmitAssessTranResult;
import com.ptt.sqm.model.SuggestionImage;
import com.ptt.sqm.model.SummaryAssess;
import com.ptt.sqm.model.UpdateAssessTranResult;
import com.ptt.sqm.session.SavedAssessTran;
import com.ptt.sqm.session.SavedSummaryAssess;
import com.ptt.sqm.util.AppUtil;
import com.ptt.sqm.util.WebserviceUtil;
import com.ptt.sqm.util.WidgetUtil;
import com.ptt.sqm.ws.AsyncResponse;
import com.ptt.sqm.ws.DecrementCallback;
import com.ptt.sqm.ws.DefaultTask;
import com.ptt.sqm.ws.DownloadCall;
import com.ptt.sqm.ws.UploadCall;
import com.ptt.sqmonmobile.R;

/**
 * A simple {@link Fragment} subclass. Activities that contain this fragment
 * must implement the {@link SummaryCommentAssess.OnFragmentInteractionListener}
 * interface to handle interaction events. Use the
 * {@link SummaryCommentAssess#newInstance} factory method to create an instance
 * of this fragment.
 * 
 */
public class SummarySuggestionFragment extends DefaultFragment implements ColorPickerDialog.OnColorChangedListener, AsyncResponse, DecrementCallback {

	private static SummarySuggestionFragment fragment;

	private OnFragmentInteractionListener mListener;

	// Create Webservice class object
	private DefaultTask mTask = null;

	private UploadCall uploadCall = null;

	private DownloadCall downloadCall = null;

	private Map<String, SummaryAssess> summaryAssess = new TreeMap<String, SummaryAssess>();

	private SavedAssessTran savedTranPref;

	private AssessItemList items;

	private AssessTran saveAssessTran;

	private String projCycleStationId;

	private boolean isSubmit;

	private boolean isDrawed;

	private View mProgressView;

	private View mContentView;

	private GoogleMap map;

	private String latLng;

	private Login login;

	private int cnt;

	private boolean canBack = true;
	
	// For set AssessTran (SubjectName, ItemName)
	Map<String, String> subjectMap = new TreeMap<String, String>();
	Map<String, String> itemChoiceMap = new TreeMap<String, String>();

	MyView mv;
	AlertDialog dialog;

	public static SummarySuggestionFragment newInstance(int sectionNumber, AssessItemList items, AssessTran saveAssessTran) {
		fragment = new SummarySuggestionFragment(items, saveAssessTran);
		Bundle args = new Bundle();
		args.putInt(AppUtil.ARG_SECTION_NUMBER, sectionNumber);
		fragment.setArguments(args);

		return fragment;
	}

	public SummarySuggestionFragment(AssessItemList items, AssessTran saveAssessTran) {
		// Required empty public constructor
		this.items = items;
		this.saveAssessTran = saveAssessTran;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onViewCreated(view, savedInstanceState);
		login = session.getUserDetails();
		projCycleStationId = items.projectId + AppUtil.UNDER_SCROLL + items.cycleAssessId + AppUtil.UNDER_SCROLL + items.stationId + AppUtil.UNDER_SCROLL + login.User_Group_Code;

		// handle Back Pressed
		handleBackPressed();

		SavedSummaryAssess saveSummaryPref = new SavedSummaryAssess(getActivity().getApplicationContext());
		summaryAssess = saveSummaryPref.loadMap(projCycleStationId);

		// Loading...
		mProgressView = view.findViewById(R.id.progress);
		mContentView = view.findViewById(R.id.container);

		// is AssessTran submitted?
		if (saveAssessTran.Status == null || saveAssessTran.Status.equalsIgnoreCase(AppUtil.ASSESS_STATUS_SUBMIT))
			isSubmit = true;

		// Set AssessTran (SubjectName, ItemName)
		setSubjectAndItemName();

		setCustInput(R.id.owner_name, R.string.owner, saveAssessTran.OwnerName);
		setCustInput(R.id.owner_tel, R.string.tel, saveAssessTran.OwnerTel);
		setCustInput(R.id.owner_email, R.string.email, saveAssessTran.OwnerEmail);

		if (saveAssessTran.OwnerTel == null || saveAssessTran.OwnerEmail == null || saveAssessTran.OwnerTel.length() == 0 || saveAssessTran.OwnerEmail.length() == 0) {
			setCustomerInfo();
		}

		// Set SuggestionList
		setSuggestionList();

		if (saveAssessTran.SignatureImageKey != null && saveAssessTran.SignatureImageKey.length() != 0) {
			downloadCall = DownloadCall.getInstance();
			mTask = new DefaultTask(downloadCall, getString(R.string.img_url) + saveAssessTran.SignatureImageKey);
			mTask.delegate = fragment;
			mTask.execute();

			isDrawed = true;

			Button clearBtn = (Button) getView().findViewById(R.id.signature_clear);
			clearBtn.setVisibility(Button.GONE);

		} else {
			mv = new MyView(getActivity());
			mv.setDrawingCacheEnabled(true);
			mv.setBackgroundResource(R.color.content_bg);// set the back
			// ground if
			// you

			ViewGroup parent = (ViewGroup) getView().findViewById(R.id.signature_layout);
			parent.addView(mv);

			mPaint = new Paint();
			mPaint.setAntiAlias(true);
			mPaint.setDither(true);
			mPaint.setColor(Color.BLACK);
			mPaint.setStyle(Paint.Style.STROKE);
			mPaint.setStrokeJoin(Paint.Join.ROUND);
			mPaint.setStrokeCap(Paint.Cap.ROUND);
			mPaint.setStrokeWidth(5);
			mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 }, 0.4f, 6, 3.5f);
			mBlur = new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL);

		}

		// Sample Data
		((TextView) getView().findViewById(R.id.station)).setText(items.stationId + AppUtil.SPACE + items.stationName);
		((TextView) getView().findViewById(R.id.project_assess)).setText(items.projectName);
		((TextView) getView().findViewById(R.id.cycle_assess)).setText(items.cycle);
		TextView assessDate = (TextView) view.findViewById(R.id.assess_date);
		((TextView) getView().findViewById(R.id.pbl)).setText(items.locationId);
		TextView fullnameAssess = (TextView) view.findViewById(R.id.fullname_assess);
		TextView groupAssess = (TextView) view.findViewById(R.id.group_assess);

		assessDate.setText(AppUtil.formatter_EN_FULL3.format(saveAssessTran.CreateDate));
		if (login.isAdmin()) {
			fullnameAssess.setText(saveAssessTran.UserName);
			groupAssess.setText(saveAssessTran.UserTypeName);
		} else {
			fullnameAssess.setText(login.User_Name);
			groupAssess.setText(login.User_Group_Name);
		}

		Button saveCmtBtn = (Button) getView().findViewById(R.id.save_assess);
		if (isSubmit) {
			saveCmtBtn.setVisibility(Button.GONE);
			((TextView) getView().findViewById(R.id.submit_date_prompt)).setVisibility(TextView.VISIBLE);
			((TextView) getView().findViewById(R.id.submit_date)).setVisibility(TextView.VISIBLE);
			((TextView) getView().findViewById(R.id.submit_date)).setText(AppUtil.formatter_EN_FULL3.format(saveAssessTran.SubmitDate));
		} else {
			((TextView) getView().findViewById(R.id.submit_date_prompt)).setVisibility(TextView.INVISIBLE);
			((TextView) getView().findViewById(R.id.submit_date)).setVisibility(TextView.INVISIBLE);
		}
		saveCmtBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				canBack = false;
				WidgetUtil.showProgress(mContentView, mProgressView, true);

				if ((saveAssessTran.SignatureImageKey == null || saveAssessTran.SignatureImageKey.length() == 0) && isDrawed) {
					uploadCall = UploadCall.getInstance();

					String guid = UUID.randomUUID().toString() + AppUtil.JPG_TYPE;
					saveAssessTran.SignatureImageKey = guid;

					Log.i("SignatureImageKey", saveAssessTran.SignatureImageKey);
					PropertyInfo nameProp = new PropertyInfo();
					nameProp.setValue(guid);
					nameProp.setType(String.class);

					PropertyInfo bitmapProp = new PropertyInfo();
					bitmapProp.setValue(mv.getDrawingCache());
					bitmapProp.setType(Bitmap.class);

					mTask = new DefaultTask(uploadCall, getString(R.string.http_url), Boolean.FALSE);
					mTask.delegate = fragment;
					mTask.execute(nameProp, bitmapProp);
				} else {
					saveImageOnServer(false);
				}
			}
		});

		Button submitCmtBtn = (Button) getView().findViewById(R.id.submit_assess);
		if (isSubmit)
			submitCmtBtn.setVisibility(Button.GONE);
		submitCmtBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				canBack = false;
				WidgetUtil.showProgress(mContentView, mProgressView, true);

				submitAssessTran();
			}
		});

		Button subjectCmtBtn = (Button) getView().findViewById(R.id.subject_assess);
		subjectCmtBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				savedTranPref.saveMap(projCycleStationId, saveAssessTran);

				FragmentManager fragmentManager = getFragmentManager();
				FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
				// fragmentTransaction.setCustomAnimations(R.anim.pop_enter,
				// R.anim.pop_exit).addToBackStack(null)
				// .replace(R.id.container,
				// MakeAssessFragment.newInstance(getArguments().getInt(AppUtil.ARG_SECTION_NUMBER),
				// items, true)).commit();
				fragmentTransaction.addToBackStack(null).replace(R.id.container, MakeAssessFragment.newInstance(getArguments().getInt(AppUtil.ARG_SECTION_NUMBER), items, true)).commit();

			}
		});

		Button summaryCmtBtn = (Button) getView().findViewById(R.id.summary_assess);
		summaryCmtBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				savedTranPref.saveMap(projCycleStationId, saveAssessTran);

				FragmentManager fragmentManager = getFragmentManager();
				FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
				fragmentTransaction.setCustomAnimations(R.anim.pop_enter, R.anim.pop_exit).addToBackStack(null)
					.replace(R.id.container, SummaryAssessFragment.newInstance(getArguments().getInt(AppUtil.ARG_SECTION_NUMBER), items, saveAssessTran)).commit();

			}
		});

		Button cancelCmtBtn = (Button) getView().findViewById(R.id.cancel_assess);
		cancelCmtBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				AlertDialog.Builder cancelConfirm = new AlertDialog.Builder(getActivity());

				cancelConfirm.setTitle(getString(R.string.alert_confirm_cancel));
				cancelConfirm.setNegativeButton("Cancel", null);
				cancelConfirm.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
					public void onClick(DialogInterface dialog, int arg1) {

						savedTranPref.saveMap(projCycleStationId, saveAssessTran);

						FragmentManager fragmentManager = getFragmentManager();

						WidgetUtil.backPress(getActivity());

					}
				});
				cancelConfirm.show();

			}
		});

		Button clearBtn = (Button) getView().findViewById(R.id.signature_clear);
		clearBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub

				mv = new MyView(getActivity());
				mv.setDrawingCacheEnabled(true);
				mv.setBackgroundResource(R.color.content_bg);

				ViewGroup parent = (ViewGroup) getView().findViewById(R.id.signature_layout);
				parent.removeAllViews();
				parent.addView(mv);

				isDrawed = false;

			}
		});

	}

	private void setCustomerInfo() {
		// TODO Auto-generated method stub
		PropertyInfo stationProp = new PropertyInfo();

		stationProp.setName("StationId");
		stationProp.setValue(saveAssessTran.StationId);
		stationProp.setType(String.class);

		mTask = new DefaultTask(com, getString(R.string.method_getcustomerinfo));
		mTask.delegate = fragment;
		mTask.execute(stationProp);
	}

	private void refreshSuggestion() {

		if (saveAssessTran.SignatureImageKey != null && saveAssessTran.SignatureImageKey.length() != 0) {
			downloadCall = DownloadCall.getInstance();
			mTask = new DefaultTask(downloadCall, getString(R.string.img_url) + saveAssessTran.SignatureImageKey);
			mTask.delegate = fragment;
			mTask.execute();

			isDrawed = true;

			Button clearBtn = (Button) getView().findViewById(R.id.signature_clear);
			clearBtn.setVisibility(Button.GONE);
		}

		if (isSubmit) {
			Button submitCmtBtn = (Button) getView().findViewById(R.id.submit_assess);
			Button saveCmtBtn = (Button) getView().findViewById(R.id.save_assess);

			submitCmtBtn.setVisibility(Button.GONE);
			saveCmtBtn.setVisibility(Button.GONE);

			TextView mName = (TextView) getView().findViewById(R.id.owner_name);
			mName.setText(saveAssessTran.OwnerName);
			mName.setEnabled(false);
			mName.setClickable(false);
			TextView mTel = (TextView) getView().findViewById(R.id.owner_tel);
			mTel.setText(saveAssessTran.OwnerTel);
			mTel.setEnabled(false);
			mTel.setClickable(false);
			TextView mEmail = (TextView) getView().findViewById(R.id.owner_email);
			mEmail.setText(saveAssessTran.OwnerEmail);
			mEmail.setEnabled(false);
			mEmail.setClickable(false);
			((TextView) getView().findViewById(R.id.submit_date_prompt)).setVisibility(TextView.VISIBLE);
			((TextView) getView().findViewById(R.id.submit_date)).setVisibility(TextView.VISIBLE);
			((TextView) getView().findViewById(R.id.submit_date)).setText(AppUtil.formatter_EN_FULL3.format(saveAssessTran.SubmitDate));
		}

	}

	private void setSuggestionList() {
		// TODO Auto-generated method stub
		TableLayout table = (TableLayout) getView().findViewById(R.id.suggestion_list);

		TableRow row;
		String aSubjectName = "";
		for (AssessSubject5019 subject : saveAssessTran.Subjects.get(0).AssessSubject5019Map.values()) {

			for (AssessItemChoice5018 item : subject.Items.get(0).AssessItemChoiceMap.values()) {
				if (!aSubjectName.equals(item.AssessSubjectName) || aSubjectName.length() == 0) {
					row = (TableRow) LayoutInflater.from(getActivity()).inflate(R.layout.subject_row, null);
					((TextView) row.findViewById(R.id.subject_value)).setText(item.AssessSubjectName);
					table.addView(row);
					aSubjectName = item.AssessSubjectName;

				}
				if (item.Suggestions != null && item.Suggestions.size() != 0) {
					Map<String, AssessSuggestion5034> AssessSuggestion5034Map = item.Suggestions.get(0).AssessSuggestion5034Map;
					for (int index = 0; index < AssessSuggestion5034Map.size(); index++) {
						AssessSuggestion5034 current;
						current = AssessSuggestion5034Map.get(AppUtil.NEW_SUGGESTION + String.valueOf(index));

						row = (TableRow) LayoutInflater.from(getActivity()).inflate(R.layout.subject_row, null);
						((TextView) row.findViewById(R.id.subject_value)).setText(AppUtil.HYPHEN + AppUtil.SPACE + AppUtil.toString(current.AssessSuggestionDesc));
						table.addView(row);

						if (AppUtil.toString(current.AssessSuggestionDetail).length() != 0) {
							row = (TableRow) LayoutInflater.from(getActivity()).inflate(R.layout.subject_row, null);
							TextView mSuggestDetail = ((TextView) row.findViewById(R.id.subject_value));
							mSuggestDetail.setTextColor(getResources().getColor(R.color.map_prompt));
							mSuggestDetail.setText(AppUtil.toString(current.AssessSuggestionDetail));
							table.addView(row);
						}
					}
				}
			}

			StringBuilder UserComment = new StringBuilder(AppUtil.toString(subject.UserComment));
			if (UserComment.length() == 0) {
				UserComment.append(AppUtil.HYPHEN);
			}
			row = (TableRow) LayoutInflater.from(getActivity()).inflate(R.layout.subject_row, null);
			TextView mUserCmt = (TextView) row.findViewById(R.id.subject_value);
			mUserCmt.setTextColor(getResources().getColor(R.color.spinner_prompt));
			mUserCmt.setText(getString(R.string.user_comment) + AppUtil.toString(UserComment));
			table.addView(row);
		}

		table.requestLayout();

	}

	private Paint mPaint;
	private MaskFilter mEmboss;
	private MaskFilter mBlur;

	public void colorChanged(int color) {
		mPaint.setColor(color);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		// Inflate the layout for this fragment
		View rootView = inflater.inflate(R.layout.summary_suggestion, container, false);
		return rootView;
	}

	// TODO: Rename method, update argument and hook method into UI event
	public void onButtonPressed(Uri uri) {
		if (mListener != null) {
			mListener.onFragmentInteraction(uri);
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		((MainActivity) activity).onSectionAttached(getArguments().getInt(AppUtil.ARG_SECTION_NUMBER));
	}

	@Override
	public void onDetach() {
		super.onDetach();
		mListener = null;

		try {
			Fragment mapFragment = (Fragment) getFragmentManager().findFragmentById(R.id.gmap);
			if (mapFragment != null) {
				FragmentManager fragmentManager = getActivity().getFragmentManager();
				FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
				fragmentTransaction.remove(mapFragment);
				fragmentTransaction.commit();
			}
		} catch (Exception e) {
		}
	}

	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();

		// Saved Item Assess on pref
		if (projCycleStationId != null) {
			savedTranPref.saveMap(projCycleStationId, saveAssessTran);

			Log.i("onStop", "Save Draft on this device");
		}

		try {
			Fragment mapFragment = (Fragment) getFragmentManager().findFragmentById(R.id.gmap);
			if (mapFragment != null) {
				FragmentManager fragmentManager = getActivity().getFragmentManager();
				FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
				fragmentTransaction.remove(mapFragment);
				fragmentTransaction.commit();
			}
		} catch (Exception e) {
		}
	}

	/**
	 * This interface must be implemented by activities that contain this
	 * fragment to allow an interaction in this fragment to be communicated to
	 * the activity and potentially other fragments contained in that activity.
	 * <p>
	 * See the Android Training lesson <a href=
	 * "http://developer.android.com/training/basics/fragments/communicating.html"
	 * >Communicating with Other Fragments</a> for more information.
	 */
	public interface OnFragmentInteractionListener {
		// TODO: Update argument type and name
		public void onFragmentInteraction(Uri uri);
	}

	public class MyView extends View {

		private static final float MINP = 0.25f;
		private static final float MAXP = 0.75f;
		private Bitmap mBitmap;
		private Canvas mCanvas;
		private Path mPath;
		private Paint mBitmapPaint;
		Context context;

		public MyView(Context c) {
			super(c);
			context = c;
			mPath = new Path();
			mBitmapPaint = new Paint(Paint.DITHER_FLAG);

		}

		@Override
		protected void onSizeChanged(int w, int h, int oldw, int oldh) {
			super.onSizeChanged(w, h, oldw, oldh);
			mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
			mCanvas = new Canvas(mBitmap);

		}

		@Override
		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);

			canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);

			canvas.drawPath(mPath, mPaint);
		}

		private float mX, mY;
		private static final float TOUCH_TOLERANCE = 4;

		private void touch_start(float x, float y) {
			// showDialog();
			mPath.reset();
			mPath.moveTo(x, y);
			mX = x;
			mY = y;

		}

		private void touch_move(float x, float y) {
			float dx = Math.abs(x - mX);
			float dy = Math.abs(y - mY);
			if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
				mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
				mX = x;
				mY = y;

				if (!isDrawed) {
					getLocationService();
				}
				isDrawed = true;
			}
		}

		private void touch_up() {
			mPath.lineTo(mX, mY);
			// commit the path to our offscreen
			mCanvas.drawPath(mPath, mPaint);
			// kill this so we don't double draw
			mPath.reset();
			// mPaint.setXfermode(new
			// PorterDuffXfermode(PorterDuff.Mode.SCREEN));
			// mPaint.setMaskFilter(null);
		}

		@Override
		public boolean onTouchEvent(MotionEvent event) {
			float x = event.getX();
			float y = event.getY();

			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				touch_start(x, y);
				invalidate();
				break;
			case MotionEvent.ACTION_MOVE:

				touch_move(x, y);
				invalidate();
				break;
			case MotionEvent.ACTION_UP:
				touch_up();
				invalidate();
				break;
			}
			return true;
		}

		public Bitmap getmBitmap() {
			return mBitmap;
		}

		public void setmBitmap(Bitmap mBitmap) {
			this.mBitmap = mBitmap;
		}

	}

	private void setCustInput(final int inputId, final int titleId, String saveText) {
		// TODO Auto-generated method stub
		TextView mInput = (TextView) getView().findViewById(inputId);
		mInput.setText(saveText);
		if (!isSubmit) {
			mInput.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
					alert.setTitle(getString(titleId));
					LayoutInflater factory = LayoutInflater.from(getActivity());
					final View textEntryView = factory.inflate(R.layout.single_input, null);

					final EditText mSingleText = (EditText) textEntryView.findViewById(R.id.single_input);
					final TextView mText = (TextView) getView().findViewById(inputId);
					mSingleText.setText(mText.getText().toString(), TextView.BufferType.SPANNABLE);
					mSingleText.setSelection(mText.getText().toString().length());

					alert.setView(textEntryView);

					alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							// String value = input.getText().toString();

							mText.setText(mSingleText.getText().toString());

							if (R.id.owner_name == inputId)
								saveAssessTran.OwnerName = mSingleText.getText().toString();
							else if (R.id.owner_tel == inputId)
								saveAssessTran.OwnerTel = mSingleText.getText().toString();
							else if (R.id.owner_email == inputId)
								saveAssessTran.OwnerEmail = mSingleText.getText().toString();

							return;
						}
					});

					alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							return;
						}
					});

					final AlertDialog dialog = alert.create();
					dialog.show();

					List<View> errors = new ArrayList<View>();
					errors.add((EditText) textEntryView.findViewById(R.id.single_input));

					int maxlength = 0;
					if (R.id.owner_name == inputId)
						maxlength = Integer.parseInt(getString(R.string.maxlength_alphameric));
					else if (R.id.owner_tel == inputId)
						maxlength = Integer.parseInt(getString(R.string.maxlength_numeric));
					else if (R.id.owner_email == inputId)
						maxlength = Integer.parseInt(getString(R.string.maxlength_numeric));

					WidgetUtil.validateMaxlengthData(getActivity(), (EditText) textEntryView.findViewById(R.id.single_input), dialog, maxlength, errors);

					if (R.id.owner_email == inputId)
						WidgetUtil.validateEmail(getActivity(), (EditText) textEntryView.findViewById(R.id.single_input), dialog, errors);
				}
			});
		}
	}

	private void setSubjectAndItemName() {
		// TODO Auto-generated method stub
		for (AssessItem assessItem : items.assessItem) {
			if (!subjectMap.containsKey(assessItem.CycleAssessSubjectId))
				subjectMap.put(assessItem.CycleAssessSubjectId, assessItem.AssessSubjectName);
			if (!itemChoiceMap.containsKey(assessItem.CycleAssessSubjectId))
				itemChoiceMap.put(assessItem.AssessItemId, assessItem.AssessItemName);
		}

	}

	private void submitAssessTran() {
		// TODO Auto-generated method stub
		if (!isDrawed) {
			Toast.makeText(getActivity(), getString(R.string.alert_no_signature), Toast.LENGTH_LONG).show();	
			canBack = true;
			WidgetUtil.showProgress(mContentView, mProgressView, false);
			return;
		}

		TextView mOwnerName = (TextView) getView().findViewById(R.id.owner_name);
		if (mOwnerName.getText().toString().length() == 0) {
			Toast.makeText(getActivity(), getString(R.string.alert_no_owner_name), Toast.LENGTH_LONG).show();
			canBack = true;
			WidgetUtil.showProgress(mContentView, mProgressView, false);
			return;
		}

		TextView mOwnerTel = (TextView) getView().findViewById(R.id.owner_tel);
		if (mOwnerTel.getText().toString().length() == 0) {
			Toast.makeText(getActivity(), getString(R.string.alert_no_owner_tel), Toast.LENGTH_LONG).show();
			canBack = true;
			WidgetUtil.showProgress(mContentView, mProgressView, false);
			return;
		}

		TextView mOwnerEmail = (TextView) getView().findViewById(R.id.owner_email);
		if (mOwnerEmail.getText().toString().length() == 0) {
			Toast.makeText(getActivity(), getString(R.string.alert_no_owner_email), Toast.LENGTH_LONG).show();
			canBack = true;
			WidgetUtil.showProgress(mContentView, mProgressView, false);
			return;
		}

		if (isItemsIncomplete()) {
			Toast.makeText(getActivity(), getString(R.string.alert_choices_incomplete), Toast.LENGTH_LONG).show();
			canBack = true;
			WidgetUtil.showProgress(mContentView, mProgressView, false);
			return;
		}

		saveAssessTran.Status = AppUtil.ASSESS_STATUS_SUBMIT;
		saveAssessTran.SubmitDate = new Date();

		if (saveAssessTran.SignatureImageKey == null || saveAssessTran.SignatureImageKey.length() == 0) {
			uploadCall = UploadCall.getInstance();

			String guid = UUID.randomUUID().toString() + AppUtil.JPG_TYPE;
			saveAssessTran.SignatureImageKey = guid;

			PropertyInfo nameProp = new PropertyInfo();
			nameProp.setValue(guid);
			nameProp.setType(String.class);

			PropertyInfo bitmapProp = new PropertyInfo();
			bitmapProp.setValue(mv.getDrawingCache());
			bitmapProp.setType(Bitmap.class);

			mTask = new DefaultTask(uploadCall, getString(R.string.http_url), Boolean.TRUE);
			mTask.delegate = fragment;
			mTask.execute(nameProp, bitmapProp);
		} else {
			saveAssessTranStep5_Submit();
		}

	}

	private boolean isItemsIncomplete() {
		// TODO Auto-generated method stub
		for (AssessItem curItem : items.assessItem) {
			AssessItemChoice5018 item = saveAssessTran.Subjects.get(0).AssessSubject5019Map.get(curItem.CycleAssessSubjectId).Items.get(0).AssessItemChoiceMap.get(curItem.AssessItemId);
			if (item.Suggestions == null || item.Suggestions.size() == 0 || item.Suggestions.get(0).AssessSuggestion5034Map == null || item.Suggestions.get(0).AssessSuggestion5034Map.size() == 0) {
				if (item.AssessChoicePoint.equals(String.valueOf(curItem.MaxPoint)) || item.AssessChoicePoint.equals(AppUtil.NA)) {

				} else if (item.AssessChoicePoint == null || item.AssessChoicePoint.length() == 0) {
					return true;
				} else {
					return true;
				}
			} else {
				if ((item.AssessChoicePoint == null || item.AssessChoicePoint.length() == 0) && !item.AssessChoicePoint.equals(AppUtil.NA)) {
					return true;
				} else {

				}
			}
		}

		return false;
	}

	private void saveAssessTranStep4_SaveDraft() {
		saveAssessTran.Status = AppUtil.ASSESS_STATUS_DRAFT;
		int grandWeightTotal = 0;
		for (SummaryAssess summary : summaryAssess.values())
			if (summary.netTotal != 0)
				grandWeightTotal += summary.weightTotal;
		saveAssessTran.TotalPoint = grandWeightTotal;

		// First Page Load
		PropertyInfo projProp = new PropertyInfo();
		projProp.setName(AppUtil.ProjectId);
		projProp.setValue(items.projectId);
		projProp.setType(String.class);

		PropertyInfo cycleProp = new PropertyInfo();
		cycleProp.setName(AppUtil.CycleAssessId);
		cycleProp.setValue(items.cycleAssessId);
		cycleProp.setType(String.class);

		PropertyInfo ResourceProp = new PropertyInfo();
		ResourceProp.setName(AppUtil.UserTypeId);
		ResourceProp.setValue(login.User_Group_Code);
		ResourceProp.setType(String.class);

		PropertyInfo StationProp = new PropertyInfo();
		StationProp.setName(AppUtil.STATIONID);
		StationProp.setValue(items.stationId);
		StationProp.setType(String.class);

		mTask = new DefaultTask(com, getString(R.string.method_getassesstranlastupdate), Boolean.TRUE);
		mTask.delegate = this;
		mTask.execute(ResourceProp, projProp, cycleProp, StationProp);

	}

	private void saveAssessTranStep5_Submit() {
		saveAssessTran.Status = AppUtil.ASSESS_STATUS_SUBMIT;
		int grandWeightTotal = 0;
		for (SummaryAssess summary : summaryAssess.values())
			if (summary.netTotal != 0)
				grandWeightTotal += summary.weightTotal;
		saveAssessTran.TotalPoint = grandWeightTotal;

		// First Page Load
		PropertyInfo projProp = new PropertyInfo();
		projProp.setName(AppUtil.ProjectId);
		projProp.setValue(items.projectId);
		projProp.setType(String.class);

		PropertyInfo cycleProp = new PropertyInfo();
		cycleProp.setName(AppUtil.CycleAssessId);
		cycleProp.setValue(items.cycleAssessId);
		cycleProp.setType(String.class);

		PropertyInfo ResourceProp = new PropertyInfo();
		ResourceProp.setName(AppUtil.UserTypeId);
		ResourceProp.setValue(login.User_Group_Code);
		ResourceProp.setType(String.class);

		PropertyInfo StationProp = new PropertyInfo();
		StationProp.setName(AppUtil.STATIONID);
		StationProp.setValue(items.stationId);
		StationProp.setType(String.class);

		mTask = new DefaultTask(com, getString(R.string.method_getassesstranlastupdate), Boolean.FALSE);
		mTask.delegate = this;
		mTask.execute(ResourceProp, projProp, cycleProp, StationProp);

	}

	@Override
	public void processFinish(String method, Object output) {
		// TODO Auto-generated method stub
		try {
			if (method.equals(getString(R.string.method_savedraftassesstran))) {
				getSaveDraft(method, output);
			} else if (method.equals(getString(R.string.method_submitassesstran))) {
				getSubmit(method, output);
			} else if (method.equals(getString(R.string.method_getassesstran))) {
				getAssessTran(method, output);
			} else if (method.startsWith(getString(R.string.img_url))) {
				DownloadImage(method, output);
			} else if (method.equals(getString(R.string.method_getcustomerinfo))) {
				getCustomerInfo(method, output);
			}
		} catch (Exception e) {
			Log.i("error", e.toString());
		}

	}

	@Override
	public void processFinish(String method, Object output, Object... objects) {
		// TODO Auto-generated method stub

		try {
			if (method.equals(getString(R.string.http_url))) {
				if (objects.length > 1) {
					UploadImage(method, output, objects);
				} else {
					UploadSignatureImage(method, output, objects);
				}

			} else if (method.equals(getString(R.string.method_getassesstranlastupdate))) {
				getAssessTranLastUpdate(method, output, objects);
			}
		} catch (Exception e) {
			Log.i("error", e.toString());
		}
	}

	private void getAssessTranLastUpdate(String method, Object output, Object... objects) {
		// TODO Auto-generated method stub
		try {
			AssessTranList assessTranLastUpdate = (AssessTranList) gson.fromJson((String) output, AssessTranList.class);
			if (assessTranLastUpdate != null) {
				saveAssessTran.RESOURCE_ID = assessTranLastUpdate.AssessTran5016_LasteUpdate.get(0).RESOURCE_ID;
				if (assessTranLastUpdate.AssessTran5016_LasteUpdate.get(0).Status.equals(AppUtil.ASSESS_STATUS_SUBMIT)) {

					Toast.makeText(getActivity(), getString(R.string.alert_already_submit), Toast.LENGTH_LONG).show();

					savedTranPref.ClearSavedAssessTran(projCycleStationId);
					isSubmit = false;

					PropertyInfo projProp = new PropertyInfo();
					projProp.setName(AppUtil.ProjectId);
					projProp.setValue(items.projectId);
					projProp.setType(String.class);

					PropertyInfo cycleProp = new PropertyInfo();
					cycleProp.setName(AppUtil.CycleAssessId);
					cycleProp.setValue(items.cycleAssessId);
					cycleProp.setType(String.class);

					PropertyInfo ResourceProp = new PropertyInfo();
					ResourceProp.setName(AppUtil.RESOURCE_ID);
					ResourceProp.setValue(saveAssessTran.RESOURCE_ID);
					ResourceProp.setType(String.class);

					PropertyInfo StationProp = new PropertyInfo();
					StationProp.setName(AppUtil.STATIONID);
					StationProp.setValue(items.stationId);
					StationProp.setType(String.class);

					mTask = new DefaultTask(com, getString(R.string.method_getassesstran));
					mTask.delegate = this;
					mTask.execute(ResourceProp, projProp, cycleProp, StationProp);
					return;
				}
			}

			boolean isDraft = ((Boolean) objects[0]).booleanValue();

			if (isDraft) {
				PropertyInfo saveAssessProp = new PropertyInfo();
				saveAssessProp.setName(AssessTran.AssessTranParam);
				saveAssessProp.setValue(WebserviceUtil.getAssessTran(AssessTran.AssessTranParam, saveAssessTran));
				saveAssessProp.setType(SoapObject.class);

				mTask = new DefaultTask(com, getString(R.string.method_savedraftassesstran));
				mTask.delegate = fragment;
				mTask.execute(saveAssessProp);

			} else {
				PropertyInfo stationProp = new PropertyInfo();
				stationProp.setName(AppUtil.StationName);
				stationProp.setValue(saveAssessTran.StationId + AppUtil.SPACE + saveAssessTran.StationName);
				stationProp.setType(String.class);

				PropertyInfo projectProp = new PropertyInfo();
				projectProp.setName(AppUtil.ProjectName);
				projectProp.setValue(saveAssessTran.ProjectName);
				projectProp.setType(String.class);

				PropertyInfo cycleProp = new PropertyInfo();
				cycleProp.setName(AppUtil.CycleName);
				cycleProp.setValue(saveAssessTran.CycleName);
				cycleProp.setType(String.class);

				PropertyInfo saveAssessProp = new PropertyInfo();
				saveAssessProp.setName(AssessTran.AssessTranParam);
				saveAssessProp.setValue(WebserviceUtil.getAssessTran(AssessTran.AssessTranParam, saveAssessTran));
				saveAssessProp.setType(SoapObject.class);

				mTask = new DefaultTask(com, getString(R.string.method_submitassesstran));
				mTask.delegate = fragment;
				mTask.execute(stationProp, projectProp, cycleProp, saveAssessProp);

			}

			Log.i(method, "Call WS Success");
		} catch (Exception e) {
			Log.i(method, "Call WS Failed");
			canBack = true;
			WidgetUtil.showProgress(mContentView, mProgressView, false);
		}
	}

	private void DownloadImage(String method, Object output) {
		// TODO Auto-generated method stub
		LinearLayout signatureLayout = (LinearLayout) getView().findViewById(R.id.signature_layout);
		signatureLayout.removeAllViews();
		ImageView signatureImg = new ImageView(getActivity().getApplicationContext());
		signatureImg.setImageBitmap((Bitmap) output);

		signatureLayout.addView(signatureImg);

	}

	private void UploadSignatureImage(String method, Object output, Object... objects) {
		// TODO Auto-generated method stub
		boolean isSubmit = ((Boolean) objects[0]).booleanValue();
		try {

			int serverResponseCode = Integer.parseInt((String) output);
			if (serverResponseCode == 200) {
				saveImageOnServer(isSubmit);
			} else {
				saveAssessTran.SignatureImageKey = null;
				Toast.makeText(getActivity(), getString(R.string.alert_submit_failed), Toast.LENGTH_LONG).show();
				canBack = true;
				WidgetUtil.showProgress(mContentView, mProgressView, false);
			}

		} catch (Exception e) {
			saveAssessTran.SignatureImageKey = null;
			Toast.makeText(getActivity(), getString(R.string.alert_submit_failed), Toast.LENGTH_LONG).show();
			canBack = true;
			WidgetUtil.showProgress(mContentView, mProgressView, false);
		}

	}

	private void UploadImage(String method, Object output, Object... objects) {
		// TODO Auto-generated method stub
		boolean isSubmit = ((Boolean) objects[0]).booleanValue();
		SuggestionImage image = (SuggestionImage) objects[1];
		int serverResponseCode = 0;
		try {
			serverResponseCode = Integer.parseInt((String) output);
			if (serverResponseCode == 200) {
				if (isSubmit) {
					WidgetUtil.deleteImageOnDevice(getActivity(), new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), getString(R.string.image_path) + AppUtil.PATH
						+ image.FILE_SAVE_NAME));
					WidgetUtil.deleteImageOnDevice(getActivity(), image.FILE_ORIGINAL_NAME);
				}
				onDecrementCount(isSubmit);
			} else {
				Toast.makeText(getActivity(), getString(R.string.alert_save_image_failed), Toast.LENGTH_LONG).show();
				canBack = true;
				WidgetUtil.showProgress(mContentView, mProgressView, false);
			}

		} catch (Exception e) {
			Toast.makeText(getActivity(), getString(R.string.alert_save_image_failed), Toast.LENGTH_LONG).show();
			canBack = true;
			WidgetUtil.showProgress(mContentView, mProgressView, false);
		}

	}

	private void getAssessTran(String method, Object output) {
		// TODO Auto-generated method stub
		try {
			saveAssessTran = (AssessTran) gson.fromJson((String) output, AssessTran.class);

			saveAssessTran.StationName = items.stationName;
			saveAssessTran.ProjectName = items.projectName;
			saveAssessTran.CycleName = items.cycle;

			generateAssessItem();

			refreshSuggestion();

			Log.i(method, "Call WS Success");
		} catch (Exception e) {
		}

		canBack = true;
		WidgetUtil.showProgress(mContentView, mProgressView, false);
	}

	private void generateAssessItem() {
		// TODO Auto-generated method stub
		if (saveAssessTran.Status == null || saveAssessTran.Status.equalsIgnoreCase(AppUtil.ASSESS_STATUS_SUBMIT)) {
			isSubmit = true;
		}

		for (AssessSubject5019 subject : saveAssessTran.Subjects.get(0).AssessSubject5019) {
			for (AssessItemChoice5018 item : subject.Items.get(0).AssessItemChoice) {
				subject.Items.get(0).AssessItemChoiceMap.put(item.AssessItemId, item);
				if (!saveAssessTran.Subjects.get(0).AssessSubject5019Map.containsKey(item.CycleAssessSubjectId))
					saveAssessTran.Subjects.get(0).AssessSubject5019Map.put(item.CycleAssessSubjectId, subject);
				item.AssessSubjectName = subjectMap.get(item.CycleAssessSubjectId);
				item.AssessItemName = itemChoiceMap.get(item.AssessItemId);
				if (item.Suggestions != null) {
					for (AssessSuggestion5034 suggestion : item.Suggestions.get(0).AssessSuggestion5034) {
						item.Suggestions.get(0).AssessSuggestion5034Map.put(AppUtil.NEW_SUGGESTION + suggestion.AssessSuggestionIndex, suggestion);
					}
				}
			}
		}

		savedTranPref.saveMap(projCycleStationId, saveAssessTran);

	}

	private void getSubmit(String method, Object output) {
		// TODO Auto-generated method stub
		output = "{" + output + "}";
		try {
			SubmitAssessTranResult SubmitAssessTranResult = (SubmitAssessTranResult) gson.fromJson((String) output, SubmitAssessTranResult.class);

			Toast.makeText(getActivity(), getString(R.string.alert_submit_success), Toast.LENGTH_LONG).show();

			savedTranPref.ClearSavedAssessTran(projCycleStationId);
			isSubmit = false;

			PropertyInfo projProp = new PropertyInfo();
			projProp.setName(AppUtil.ProjectId);
			projProp.setValue(items.projectId);
			projProp.setType(String.class);

			PropertyInfo cycleProp = new PropertyInfo();
			cycleProp.setName(AppUtil.CycleAssessId);
			cycleProp.setValue(items.cycleAssessId);
			cycleProp.setType(String.class);

			PropertyInfo ResourceProp = new PropertyInfo();
			ResourceProp.setName(AppUtil.RESOURCE_ID);
			ResourceProp.setValue(saveAssessTran.RESOURCE_ID);
			ResourceProp.setType(String.class);

			PropertyInfo StationProp = new PropertyInfo();
			StationProp.setName(AppUtil.STATIONID);
			StationProp.setValue(items.stationId);
			StationProp.setType(String.class);

			mTask = new DefaultTask(com, getString(R.string.method_getassesstran));
			mTask.delegate = this;
			mTask.execute(ResourceProp, projProp, cycleProp, StationProp);

			Log.i(method, "Call WS Success");
		} catch (Exception e) {
			Log.i(method, "Call WS Failed");
		}
	}

	private void getSaveDraft(String method, Object output) {
		// TODO Auto-generated method stub
		output = "{" + output + "}";
		try {
			SaveDraftAssessTranResult SaveDraftAssessTranResult = (SaveDraftAssessTranResult) gson.fromJson((String) output, SaveDraftAssessTranResult.class);

			Toast.makeText(getActivity(), getString(R.string.alert_save_draft), Toast.LENGTH_LONG).show();

			savedTranPref.ClearSavedAssessTran(projCycleStationId);
			isSubmit = false;

			PropertyInfo projProp = new PropertyInfo();
			projProp.setName(AppUtil.ProjectId);
			projProp.setValue(items.projectId);
			projProp.setType(String.class);

			PropertyInfo cycleProp = new PropertyInfo();
			cycleProp.setName(AppUtil.CycleAssessId);
			cycleProp.setValue(items.cycleAssessId);
			cycleProp.setType(String.class);

			PropertyInfo ResourceProp = new PropertyInfo();
			ResourceProp.setName(AppUtil.RESOURCE_ID);
			ResourceProp.setValue(saveAssessTran.RESOURCE_ID);
			ResourceProp.setType(String.class);

			PropertyInfo StationProp = new PropertyInfo();
			StationProp.setName(AppUtil.STATIONID);
			StationProp.setValue(items.stationId);
			StationProp.setType(String.class);

			mTask = new DefaultTask(com, getString(R.string.method_getassesstran));
			mTask.delegate = this;
			mTask.execute(ResourceProp, projProp, cycleProp, StationProp);

			Log.i(method, "Call WS Success");
		} catch (Exception e) {
			Log.i(method, "Call WS Failed");
		}
	}

	private void getCustomerInfo(String method, Object output) {
		// TODO Auto-generated method stub
		try {

			CustomerInfo custInfo = (CustomerInfo) gson.fromJson((String) output, CustomerInfo.class);

			if (custInfo != null) {
				if (saveAssessTran.OwnerTel == null || saveAssessTran.OwnerTel.length() == 0)
					setCustInput(R.id.owner_tel, R.string.tel, custInfo.MOBILE_NO);
				if (saveAssessTran.OwnerEmail == null || saveAssessTran.OwnerEmail.length() == 0)
					setCustInput(R.id.owner_email, R.string.email, custInfo.EMAIL);
			}

			Log.i(method, "Call WS Success");

		} catch (Exception e) {
			Log.i(method, "Call WS Failed");
		}

	}

	private void getLocationService() {
		try {
			// Google map
			if (login.isAdmin()) {
				try {
					Fragment mapFragment = (Fragment) getFragmentManager().findFragmentById(R.id.gmap);
					if (mapFragment != null) {
						FragmentManager fragmentManager = getActivity().getFragmentManager();
						FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
						fragmentTransaction.remove(mapFragment);
						fragmentTransaction.commit();
					}
				} catch (Exception e) {
				}
				return;
			}

			map = ((MapFragment) getFragmentManager().findFragmentById(R.id.gmap)).getMap();

			map.setOnMyLocationChangeListener(new OnMyLocationChangeListener() {

				@Override
				public void onMyLocationChange(Location location) {
					// TODO Auto-generated method stub
					try {

						// if (saveAssessTran.GPSLocation == null ||
						// saveAssessTran.GPSLocation.length() == 0) {
						latLng = String.valueOf(location.getLatitude()) + AppUtil.COMMA + String.valueOf(location.getLongitude());
						saveAssessTranStep2_saveGPSLocation(latLng);
						// Toast.makeText(getActivity(), latLng,
						// Toast.LENGTH_LONG).show();
						// }

					} catch (Exception e) {

					} finally {
						map.setMyLocationEnabled(false);
					}
				}

			});

			if (map != null) {
				map.setMyLocationEnabled(true);
			}

		} catch (Exception e) {
			Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_LONG).show();
		}
	}

	private void saveAssessTranStep2_saveGPSLocation(String GPSLocation) {
		saveAssessTran.GPSLocation = GPSLocation;
	}

	private void saveImageOnServer(boolean isSubmit) {
		// TODO Auto-generated method stub
		List<SuggestionImage> deviceImages = new ArrayList<SuggestionImage>();
		List<SuggestionImage> serverImages = new ArrayList<SuggestionImage>();
		for (AssessSubject5019 subject : saveAssessTran.Subjects.get(0).AssessSubject5019Map.values()) {

			for (AssessItemChoice5018 item : subject.Items.get(0).AssessItemChoiceMap.values()) {

				if (item.AssessChoicePoint.length() != 0)

					if (item.Suggestions != null && item.Suggestions.size() != 0) {
						for (AssessSuggestion5034 suggestion : item.Suggestions.get(0).AssessSuggestion5034Map.values()) {
							if (suggestion.Images != null && suggestion.Images.size() != 0) {
								for (SuggestionImage image : suggestion.Images.get(0).SuggestionImage) {
									// CR 107, 108
									if (image.CreatedDt == null || image.CreatedDt.length() == 0) {
										deviceImages.add(image);
									} else {
										serverImages.add(image);
										if (isSubmit) {
											WidgetUtil.deleteImageOnDevice(getActivity(), new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
												getString(R.string.image_path) + AppUtil.PATH + image.FILE_SAVE_NAME));
											WidgetUtil.deleteImageOnDevice(getActivity(), image.FILE_ORIGINAL_NAME);
										}
									}
								}

								if (serverImages.size() != 0) {
									for (SuggestionImage image : serverImages) {
										suggestion.Images.get(0).SuggestionImage.remove(image);
									}
									serverImages = new ArrayList<SuggestionImage>();
								}

							}
						}
					}
			}
		}

		if (deviceImages.size() != 0) {
			setCount(deviceImages.size());
			for (SuggestionImage image : deviceImages) {
				uploadCall = UploadCall.getInstance();

				PropertyInfo nameProp = new PropertyInfo();
				nameProp.setValue(image.FILE_SAVE_NAME);
				nameProp.setType(String.class);

				PropertyInfo bitmapProp = new PropertyInfo();
				bitmapProp.setValue(WidgetUtil.getImageOnDevice(getActivity(), image.FILE_SAVE_NAME));
				bitmapProp.setType(Bitmap.class);

				mTask = new DefaultTask(uploadCall, getString(R.string.http_url), isSubmit, image);
				mTask.delegate = fragment;
				mTask.execute(nameProp, bitmapProp);

				Log.i("save image count", "T");
			}
		} else {
			onDecrementCount(isSubmit);
		}

	}

	private void handleBackPressed() {
		// TODO Auto-generated method stub
		getView().setFocusableInTouchMode(true);
		getView().requestFocus();
		getView().setOnKeyListener(new View.OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {

				if (keyCode == KeyEvent.KEYCODE_BACK) {
					if (canBack) {
						WidgetUtil.backPress(getActivity());
					} else {
						return true;
					}
				}

				return false;
			}
		});
	}

	@Override
	public void setCount(int cnt) {
		// TODO Auto-generated method stub
		this.cnt = cnt;
	}

	@Override
	public void onDecrementCount() {
		// TODO Auto-generated method stub
	}

	@Override
	public void onDecrementCount(View view, int cnt) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onDecrementCount(boolean flag) {
		// TODO Auto-generated method stub

		cnt--;
		if (cnt <= 0) {
			if (flag) {
				Log.i("saveAssessTranStep5_Submit", "PASS");
				saveAssessTranStep5_Submit();
			} else {
				Log.i("saveAssessTranStep4_SaveDraft", "PASS");
				saveAssessTranStep4_SaveDraft();
			}
		}

	}

}
